package com.keyidea.jfxui.core.config.log;

import com.keyidea.jfxui.core.config.context.SpringContextHelper;
import com.keyidea.jfxui.core.util.Threads;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 */
public class AsyncManager {
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_PERIOD_TIME = 1000;

    private static final Map<String, ScheduledFuture<?>> PERIOD_TASK_MAP = new HashMap<>();

    /**
     * 异步操作任务调度线程池
     */
    private final ScheduledExecutorService executor = SpringContextHelper.getBean("scheduledExecutorService");

    /**
     * 单例模式
     */
    private AsyncManager() {
    }

    private static final AsyncManager me = new AsyncManager();

    public static AsyncManager me() {
        return me;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行循环任务
     *
     * @param task 任务
     */
    public void addScheduledThreadPool(String scheduleName, TimerTask task) {
        removeScheduledThreadPool(scheduleName);
        ScheduledFuture<?> scheduledFuture = executor.scheduleAtFixedRate(task, OPERATE_DELAY_TIME, OPERATE_PERIOD_TIME, TimeUnit.MILLISECONDS);
        PERIOD_TASK_MAP.put(scheduleName, scheduledFuture);
    }


    public void removeScheduledThreadPool(String scheduleName) {
        // 判断之前的定时任务是否存在，若存在则将其停止
        if (!Objects.isNull(PERIOD_TASK_MAP.get(scheduleName))) {
            PERIOD_TASK_MAP.get(scheduleName).cancel(true);
        }
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        Threads.shutdownAndAwaitTermination(executor);
    }
}
